<template>
    <div class="main">
        <div class="head-wrap flex-jsb">
            <div class="flex">
                <el-form :model="form" :inline="true" ref="form" label-width="100px" class="form">
                    <el-form-item label="机器人名称：" prop="robotNumber">
                        <el-select size="mini" v-model="form.robotNumber" placeholder="请选择机器人">
                            <el-option :label="item.robotName" :value="item.robotNumber" :key="item.robotNumber"
                                v-for="item in selecData" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div style="width: 130px;">
                <el-button size="mini" @click="handleRset">重置</el-button>
                <el-button size="mini" type="primary" @click="handleSelect">查询</el-button>
            </div>
        </div>
        <div class="bottom-wrap mt15">
            <div class="flex-jsb mt15">
                <div></div>
                <el-button size="mini" type="primary" @click="handleCreate">新增</el-button>
            </div>
            <div class="table-wrap mt15">
                <el-table :data="logList" ref="multipleTable" height="570" style="width: 100%"
                    :cell-style="{ color: '#333' }" class="table">
                    <el-table-column prop="taskName" label="任务名称" min-width="400" show-overflow-tooltip />
                    <el-table-column prop="roomName" label="所属库房" min-width="250" show-overflow-tooltip />
                    <el-table-column prop="enable" label="任务状态" min-width="100">
                        <template slot-scope="scope">
                            <div>{{ scope.row.enable == 0 ? '启用' : '禁用' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="taskCron" label="CRON表达式" min-width="160" />
                    <el-table-column prop="taskStatus" label="最新状态" min-width="160">
                        <template slot-scope="scope">
                            <div>{{ formatLabel(scope.row.taskStatus) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="taskTime" label="最新状态时间" min-width="200">
                        <template slot-scope="scope">
                            <div>{{ formatDate(scope.row.taskTime) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" min-width="160">
                        <template slot-scope="scope">
                            <div>{{ formatDate(scope.row.createTime, "yyyy-MM-dd") }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="160" fixed="right">
                        <template v-slot="{ row, $index }">
                            <el-button v-if="row.taskStatus != 2" class="text-btn-table" type="text"
                                @click="handleExecute(row)">立即执行</el-button>
                            <el-button v-if="row.taskStatus == 2" :disabled="rowIndex == $index && flag"
                                class="text-btn-table" type="text" @click="handleStop(row, $index)">{{ btnText
                                }}</el-button>
                            <el-button class="text-btn-table" type="text" @click="handleEdit(row)">修改</el-button>
                            <el-button class="text-btn-table" type="text" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="flex-jsb">
                    <div></div>
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page.sync="form.start" :page-sizes="[10, 20, 30, 40]" :page-size="form.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="total"
                        class="ml25 mt15 systemPagination el-pagination">
                    </el-pagination>
                </div>
            </div>
        </div>
        <!-- 新增or编辑 -->
        <el-dialog :title="titleText" :show-close="false" @close="cancel" :visible.sync="dialogVisible" width="800px"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form :model="currentRow" ref="planForm" :rules="rules" label-width="140px" class="form">
                <el-row :gutter="10">
                    <el-col :span="24">
                        <el-form-item label="机器人名称：" prop="robotNumber">
                            <el-select size="mini" v-model="currentRow.robotNumber" placeholder="请选择机器人"
                                :disabled="formType == 'edit'" style="width: 100%;" @change="handleRobotChange">
                                <el-option :label="item.robotName" :value="item.robotNumber" :key="item.robotNumber"
                                    v-for="item in selecData" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="roomName" :span="24">
                        <el-form-item label="库房：" prop="roomName">
                            <el-input size="mini" disabled clearable v-model="roomName" style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="巡检任务名称：" prop="taskName">
                            <el-input size="mini" clearable v-model="currentRow.taskName" placeholder="请输入巡检任务名称"
                                style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="CRON表达式：" prop="taskCron">
                            <el-input size="mini" clearable v-model="currentRow.taskCron" placeholder="请输入CRON表达式"
                                style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="任务状态：" prop="enable">
                            <el-switch v-model="currentRow.enable" active-text="启用" :active-value="0" inactive-text="禁用"
                                :inactive-value="1">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="presetData.length" :span="24">
                        <el-form-item label="预置位配置：" prop="selectPresetData">
                            <el-transfer v-model="selectPresetData" :props="{
                                key: 'id',
                                label: 'name'
                            }" :data="presetData" :titles="['预置位列表', '已选预置位']">
                            </el-transfer>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="ok">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { robotTaskList, getRobotList, robotTaskSetting, robotTaskUpdate, robotTaskDelete, presetList, robotPresetList, detailRobotSetting, taskBingPreset, run, stop } from "@/api/rabotManageApi.js";
import utils from "@/utils/date.js";
export default {
    data() {
        return {
            presetData: [],
            selectPresetData: [],
            selecData: [],
            form: {
                robotNumber: "",
                limit: 10,
                start: 1,
            },
            logList: [],
            total: 0,
            rowIndex: "",
            flag: false,
            titleText: "新增巡检任务",
            btnText: "终止",
            dialogVisible: false,
            formType: "add",
            currentRow: {
                robotNumber: "",
                taskName: "",
                taskStatus: 0,
                taskCron: "",
                enable: "0"
            },
            roomName: "",
            currentBobot: {},
            rules: {
                robotNumber: [
                    { required: true, message: "请选择机器人", trigger: "change" },
                ],
                taskName: [
                    { required: true, message: "请输入巡检任务名称", trigger: "blur" },
                ],
                taskStatus: [
                    { required: true, message: "请选择巡检任务状态", trigger: "change" },
                ],
                taskCron: [
                    { required: true, message: "请输入CRON表达式", trigger: "blur" },
                ],
            },
            taskStatusMap: [
                {
                    label: "未执行",
                    value: 0
                },
                {
                    label: "暂停",
                    value: 1
                },
                {
                    label: "执行中",
                    value: 2
                },
                {
                    label: "执行结束",
                    value: 3
                },
                {
                    label: "执行失败",
                    value: 4
                }
            ]
        };
    },
    mounted() {
        this.getMachineRoomData();
        this.getRobotListData({ ...this.form, start: this.form.start - 1 });
    },
    methods: {
        formatLabel(row) {
            return this.taskStatusMap.find(item => item.value == row).label
        },
        getMachineRoomData() {
            getRobotList({
                limit: 999,
                start: 0,
            }).then((res) => {
                if (res.code == "200") {
                    this.selecData = res.info.map(item => {
                        return {
                            ...item,
                            robotNumber: item.robotNumber.toString()
                        }
                    });
                }
            });
        },
        getRobotListData(data) {
            robotTaskList(data).then((res) => {
                if ((res.code = "200")) {
                    this.logList = res.info;
                    this.total = res.totalCount;
                }
            });
        },
        handleSizeChange(val) {
            this.form.limit = val;
            this.form.start = 1;
            this.getRobotListData({ ...this.form, start: 0 });
        },

        handleCurrentChange(val) {
            this.form.start = val;
            this.getRobotListData({ ...this.form, start: this.form.start - 1 });
        },
        formatDate(date, str = "yyyy-MM-dd hh:mm:ss") {
            return utils.formatter(date, str);
        },
        handleRset() {
            this.form = {
                robotNumber: "",
                limit: 10,
                start: 1,
            };
            this.getRobotListData({ ...this.form, start: 0 });
        },
        handleSelect() {
            this.getRobotListData({ ...this.form, start: 0 });
        },
        handleCreate() {
            this.formType = "add";
            this.currentRow = {
                robotNumber: "",
                taskName: "",
                taskStatus: 0,
                taskCron: "",
                enable: "0"
            };
            this.dialogVisible = true;
        },
        handleExecute(row) {
            run({
                taskId: row.taskId
            }).then((res) => {
                if (res.code == 200) {
                    this.$message({
                        message: "执行成功",
                        type: "success",
                    });
                    this.getRobotListData({ ...this.form, start: 0 });
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error",
                    });
                }
            })
        },
        handleStop(row, index) {
            stop({
                taskId: row.taskId
            }).then((res) => {
                if (res.code == 200) {
                    this.rowIndex = index;
                    this.flag = true;
                    this.btnText = "正在停止";
                    this.$message({
                        message: "正在停止巡检任务，请稍等",
                        type: "success",
                    });
                    setTimeout(() => {
                        this.rowIndex = "";
                        this.flag = false;
                        this.btnText = "终止";
                        this.getRobotListData({ ...this.form, start: 0 });
                    }, 20000);
                } else {
                    this.$message({
                        message: res.msg,
                        type: "error",
                    });
                }
            })
        },
        handleEdit(row) {
            this.titleText = "编辑巡检任务";
            this.formType = "edit";
            detailRobotSetting(row.robotNumber).then(res => {
                if (res.code == 200) {
                    this.roomName = res.info.roomName;
                } else {
                    this.roomName = "";
                }
            })
            presetList({ robotNumber: row.robotNumber }).then(res => {
                if (res.code == 200) {
                    this.presetData = res.info;
                } else {
                    this.presetData = [];
                }
            })
            robotPresetList({
                taskId: row.taskId
            }).then((res) => {
                if (res.code == 200) {
                    this.selectPresetData = res.info.map(item => item.id);
                } else {
                    this.selectPresetData = []
                }
                this.currentRow = { ...row };
                this.dialogVisible = true;
            })

        },
        handleDelete(row) {
            this.$confirm("此操作将删除该巡检任务, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    robotTaskDelete(row.taskId).then((res) => {
                        if (res.code == 200) {
                            this.$message({
                                message: "删除成功",
                                type: "success",
                            });
                            this.getRobotListData({
                                ...this.form, start: 0
                            })
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error",
                            });
                        }
                    });
                })
        },
        ok() {
            this.$refs.planForm.validate((valid) => {
                if (valid) {
                    if (this.formType == "add") {
                        const params = this.selectPresetData.length ? { ...this.currentRow, presetIds: this.selectPresetData.join(",") } : this.currentRow;
                        robotTaskSetting(params).then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "添加成功",
                                    type: "success",
                                });
                                this.cancel();
                                this.getRobotListData({ ...this.form, start: 0 });
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error",
                                });
                            }
                        });
                    } else {
                        if (this.roomName && this.presetData.length) {
                            taskBingPreset({
                                presetId: this.selectPresetData.join(","),
                                taskId: this.currentRow.taskId
                            })
                        }
                        robotTaskUpdate(this.currentRow).then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "修改成功",
                                    type: "success",
                                });
                                this.cancel();
                                this.getRobotListData
                                    ({ ...this.form, start: 0 });
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error",
                                });
                            }
                        });
                    }
                }
            });
        },
        cancel() {
            this.currentRow = {
                robotNumber: "",
                taskName: "",
                taskStatus: 0,
                taskCron: "",
                enable: "0"
            };
            this.roomName = "";
            this.presetData = [];
            this.selectPresetData = [];
            this.$refs.planForm.clearValidate();
            this.dialogVisible = false;
        },
        handleRobotChange(val) {
            detailRobotSetting(val).then(res => {
                if (res.code == 200) {
                    this.roomName = res.info.roomName;
                } else {
                    this.roomName = "";
                }
            })
            this.selectPresetData = [];
            presetList({ robotNumber: val }).then(res => {
                if (res.code == 200) {
                    this.presetData = res.info;
                } else {
                    this.presetData = [];
                }
            })
        }
    },
};
</script>
<style lang="scss" scoped>
.main {
    width: 100%;
    height: 100%;
    overflow: auto;
    margin: 0 auto;

    .head-wrap {
        padding: 20px 17px;
        border-radius: 6px;

        /deep/ .el-form-item {
            margin-bottom: 0;

            .el-form-item__label {
                color: #000;
            }
        }
    }

    .head-wrap,
    .bottom-wrap {
        background: #ffffff;
        box-shadow: 0px 0px 12px 0px rgba(129, 155, 151, 0.3);
    }

    .bottom-wrap {
        padding: 0 15px;
        border-radius: 10px;
        height: 89%;
        overflow: hidden;

        .table-wrap {
            height: 100%;
            overflow: auto;
            color: #333;

            .table {
                border: 1px solid #f0f0f0;
                border-radius: 0px 0px 6px 6px;
                overflow: hidden;
            }

            /deep/ .el-table__header tr,
            /deep/ .el-table__header th {
                background-color: var(--system-table-header-bgc) !important;
                color: #333;
                font-weight: 400;
            }

            .state {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                margin-right: 5px;
            }

            .state1 {
                background: #ff9000;
            }

            .state2 {
                background: #21b795;
            }
        }
    }
}

.flex-ac {
    display: flex;
    align-items: center;
}

.mt15 {
    margin-top: 15px;
}

.flex {
    display: flex;
}

.flex-jsb {
    display: flex;
    justify-content: space-between;
}

.mt25 {
    margin-top: 25px;
}

.ml25 {
    margin-left: 25px;
}
</style>
